package com.lance.answer.question_export;


import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.XinJiangUtil;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileOutputStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 05-14 测试保存视频
 */
public class GetGkQuestionAndAnswerByTeacher {



//    https://xjskk.open.com.cn/stuspace/#/play?sId=2772092&oId=11103&type=1&
//    // resourceId=3f103667-2e50-4d64-83d2-7a2949a755f5&link=VEvclwcDATA20210328121128848.mp4&extensionName=mp4&from=menu
//
//    https://xjskk.open.com.cn/stuspace/#/play?sId=2772092&oId=11103&type=1&resourceId=
//    // ae8b29e0-0a9e-4874-b7e0-7bbe92e8049a&link=VEwuadsDATA20210328115007124.mp4&extensionName=mp4&from=menu


    public static void main(String[] args) throws Exception {
//
//        String s = "https://xjskk.open.com.cn/teacher/#/ReviewResult?id=497ec914-9d06-408d-8dd2-3e39219841b6&answerCount=1&studentHomeworkId=7bfc1d8d-7804-4317-a1d8-73b1a4d69c8e&openCourseId=27932&type=1&isSub=2&hId=3571&stuId=242759";
//        s = s.substring(s.indexOf("?id=")+4);
//        s = s.substring(0,s.indexOf("&"));
//        System.err.println(s);
//        Thread.sleep(20000);


        WebDriver driver = Util.getDriver("c:\\ynouAutoStudy\\chromedriver.exe");
        String url = "https://xjskk.open.com.cn/teacherspace-auth/#/login";
        // 打开指定的网站
        driver.get(url);
        Thread.sleep(200);

        for (WebElement we : driver.findElements(By.className("el-input__inner"))) {
            if ("text".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"liujw"});
            }
            if ("password".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"liujw"});
            }
        }
        //    driver.findElement(By.cssSelector("button[class='el-button el-button--primary']")).click();
        driver.findElement(By.cssSelector("button[class='el-button login-ruleForm-btn el-button--primary']")).click();

        Thread.sleep(18000);

        for(WebElement number:driver.findElements(By.className("number"))){
         //   if("2".equals(number.getText())){
      //      if("3".equals(number.getText())){
            if("4".equals(number.getText())){
                System.err.println("click..................");
                number.click();
            }
        }
        Thread.sleep(30000);
      //  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);


        // 当前页面的所有课程
     //   List<WebElement> courseInfoList = driver.findElements(By.cssSelector("div[class='contblockout clearfix']"));
        List<WebElement> courseInfoList = (new WebDriverWait(driver, Duration.ofSeconds(20))).until((ExpectedCondition<List<WebElement>>)
                d -> d.findElements(By.cssSelector("div[class='contblockout clearfix']")));


        /**
         * driver.get('http://www.ahaoboy.cn:2222')
         * # 强制等待
         * # time.sleep(1)
         *
         * # 隐性等待
         * # driver.implicitly_wait(1)
         */

        for (WebElement courseInfo : courseInfoList) {
            boolean isSuccess = true;
            String courseName = "";
            try {
                Thread.sleep(10000);
                // 找到当前课程 进行课程的按钮
                WebElement btnContent = courseInfo.findElement(By.cssSelector("*[class='v-btn__content']"));
                courseName = Util.dealContent(courseInfo.findElement(By.cssSelector("div[class='user-couser-info fl']")).findElement(By.tagName("span")).getText());

                // FIXME 未刷的
                if(courseName.contains("科学与技术")
                        ||courseName.contains("现代管理原理")
                        ||courseName.contains("现代教育原理")
                        ||courseName.contains("汉语通论")
                        ||courseName.contains("纳税筹划")
                        ||courseName.contains("审计案例分析")
                        ||courseName.contains("国际公法")
                        ||courseName.contains("国际私法")
                        ||courseName.contains("劳动与社会保障法")
                        ||courseName.contains("人类与社会")
                        ||courseName.contains("中国法制史")
                        ||courseName.contains("Photoshop图像处理")
                        ||courseName.contains("小学儿童教育心理学")
                        ||courseName.contains("信息技术与教育技术(1)")
                ){
                    isSuccess = false;
                    continue;
                }

                boolean isGoOn = true;
               File all = new File("D:\\xinjiang");
                for(File f:all.listFiles()){
                    if(courseName.equals(f.getName())){
                        System.err.println("题目已经获取了");
                        isSuccess = false;
                        isGoOn = false;
                        break;
                    }
                }
                if(!isGoOn){
                    isSuccess =false;
                    continue;
                }


                btnContent.click();
                // 找到当前课程的作业集合
                //  List<WebElement>  taskList = driver.findElements(By.cssSelector("*[class='el-table__row']"));

                Thread.sleep(5000);
                Util.switchToLast(driver);

                // 1.显式等待 https://blog.csdn.net/pf20050904/article/details/20052485
                List<WebElement> taskList = (new WebDriverWait(driver, Duration.ofSeconds(20))).until((ExpectedCondition<List<WebElement>>)
                        d -> d.findElements(By.cssSelector("button[class='el-button el-button--text el-button--medium']")));

                Util.switchToLast(driver);
                if (null == taskList || taskList.size() < 1) {
                    File file = new File("d:\\一体化获取课程答案为空.txt");
                    FileOutputStream outputStream = new FileOutputStream(file, true);
                    String s = courseName + "\r\n";
                    outputStream.write(s.getBytes());
                    continue;
                }

                // 2.隐式等待
//                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//                System.out.println(driver.getPageSource());
//                List<WebElement>  taskList = driver.findElements(By.cssSelector("*[class='el-table__row']"));
                System.err.println("taskList:" + taskList);

                for (int i = 0; i < taskList.size(); i++) {
                    boolean isclose = true;
                    try {
                        Thread.sleep(10000);
                        (new WebDriverWait(driver, 20)).until((ExpectedCondition<List<WebElement>>)
                                d -> d.findElements(By.cssSelector("button[class='el-button el-button--text el-button--medium']"))).get(i).click();

                        // task.click();
                        //v-tabs__item
                        List<WebElement> allItems = (new WebDriverWait(driver, Duration.ofSeconds(20))).until((ExpectedCondition<List<WebElement>>)
                                d -> d.findElements(By.cssSelector("a[class='v-tabs__item']")));
                        if (null == allItems || allItems.size() < 1) {
                            File file = new File("d:\\一体化获取课程答案为空.txt");
                            FileOutputStream outputStream = new FileOutputStream(file, true);
                            String s = courseName + "\r\n";
                            outputStream.write(s.getBytes());
                            continue;
                        }
                        for (WebElement we : allItems) {
                            if ("已批阅".equals(we.getText())) {
                                we.click();
                                break;
                            }
                        }

                        Thread.sleep(2000);
                        for (WebElement we : (new WebDriverWait(driver, Duration.ofSeconds(20))).until((ExpectedCondition<List<WebElement>>)
                                d -> d.findElements(By.cssSelector("button[type='button']")))) {
                            System.err.println("we.getText():" + we.getText());
                            if (we.getText().contains("查看明细")) {
                                we.click();
                                break;
                            }
                        }

                        //el-icon-document
                        Thread.sleep(2000);
                        List<WebElement> allButtons = (new WebDriverWait(driver, Duration.ofSeconds(20))).until((ExpectedCondition<List<WebElement>>)
                                d -> d.findElements(By.cssSelector("button[type='button']")));
                        if (null == allButtons || allButtons.size() < 1) {
                            File file = new File("d:\\一体化获取课程答案为空.txt");
                            FileOutputStream outputStream = new FileOutputStream(file, true);
                            String s = courseName + "\r\n";
                            outputStream.write(s.getBytes());
                            continue;
                        }
                        for (WebElement we : allButtons) {
                            if (we.getText().contains("批阅结果")) {
                                we.click();
                                break;
                            }
                        }

                        // 开始获取题目和答案 FIXME TODO
                        Util.switchToLast(driver);

//                String title = (new WebDriverWait(driver, Duration.ofSeconds(20))).until((ExpectedCondition<WebElement>)
//                        d -> d.findElement(By.tagName("h2"))).getText();

                        // https://xjskk.open.com.cn/api/teacher/teacher-space-service/homeworkRead/getTeacherMarkPaperInfo?answerId=497ec914-9d06-408d-8dd2-3e39219841b6

                        String currentUrl = driver.getCurrentUrl();
                        currentUrl = currentUrl.substring(currentUrl.indexOf("?id=") + 4);
                        Thread.sleep(2000);
                        String answerId = currentUrl.substring(0, currentUrl.indexOf("&"));
                        String getUrl = " https://xjskk.open.com.cn/api/teacher/teacher-space-service/homeworkRead/getTeacherMarkPaperInfo?answerId=" + answerId;
                        System.err.println("getUrl:" + getUrl);

                        Set<Cookie> cookies = driver.manage().getCookies();
                        String studentSpaceProfile = Util.getStudentSpaceProfile(cookies);
                        String authorization = Util.getAuthorization(cookies);
                        String cookie = Util.getCookie(cookies);
                        // 初始化头部
                        System.out.println("authorization:" + authorization);
                        System.out.println("studentSpaceProfile:" + studentSpaceProfile);
                        Map<String, String> heads = XinJiangUtil.initHttpHeads(studentSpaceProfile, authorization);

                        String result = HttpUtil.get(getUrl, cookie, heads);

                        String rootPath = "d://xinjiang//" + courseName + "//";
                        // FileUtils.write(new File(rootPath + answerId + ".json"), JSONObject.toJSONString(result, SerializerFeature.PrettyFormat),"utf-8");
                        FileUtils.write(new File(rootPath + answerId + ".json"), result, "utf-8");
                        FileUtils.write(new File("d://xinjiang2//" + answerId + ".json"), result, "utf-8");


                    } catch (Exception e) {
                        e.printStackTrace();
                        isclose = false;
                        Thread.sleep(300000000);
                    } finally {
                        if (isclose) {
                            driver.close();
                        }
                        Util.switchToLast(driver);
                        driver.navigate().back();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                File file = new File("d:\\一体化获取课程问题.txt");
                FileOutputStream outputStream = new FileOutputStream(file, true);
                String s = courseName + "\r\n";
                outputStream.write(s.getBytes());
                isSuccess = false;
                Thread.sleep(300000000);
            } finally {
                if (isSuccess) {
                    driver.close();
                    // break;
                }
                Thread.sleep(2000);
                Util.switchToLast(driver);
                Thread.sleep(2000);

            }

        }
        System.err.println("end");
        Thread.sleep(1000000000);
//        driver.quit();


    }


}
